using System;

using Microsoft.Cci;
using Microsoft.FxCop.Sdk;
using Microsoft.FxCop.Sdk.Introspection;

namespace Tyng.Rules
{
	public abstract class StringConstantRuleBase<T> : RuleBase<T>
        where T : StringConstantRuleBase<T>
	{
		protected StringConstantRuleBase() {}
		
		public override ProblemCollection Check(Member member)
		{
			if(member is Field)
			{
				//if its a constant, check default value
				Field field = (Field) member;

				if(field.DefaultValue != null && field.DefaultValue.Value != null)
				{
					string test = null;

					if(field.DefaultValue.Value is string)
						test = (string) field.DefaultValue.Value;
				
					if(test != null)
						if(! IsValidStringConstant(test))
							Problems.Add(new Problem(GetResolution(test), member));
				}
					
			}
			else if(member is Method) 
			{
				//if its a method, check scoped constants
				Method method = (Method) member;

				for(int i = 0; i < method.Instructions.Length; i ++)
				{
					if(method.Instructions[i].OpCode == OpCode.Ldstr)
					{
						string test = method.Instructions[i].Value as string;

						if(test != null)
							if(! IsValidStringConstant(test))
								Problems.Add(new Problem(GetResolution(test), method.Instructions[i]));
					}
				}
			}

			return Problems;
		}

		protected abstract bool IsValidStringConstant(string constant);
		
	}
}
